package com.wangjiang.foundation.common.util.bcrytpt;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.Security;

/**
 * @description: DES的BC实现
 * @author: wangjiang
 * @create: 2020-03-06 13:59
 */

public class BCDesUtils {

    public static final String ALGORITHM = "DES";
    public static final String CIPHER_ALGORITHM = ALGORITHM + "/ECB/ISO10126Padding";

    // 获取 Key
    public static byte[] getKey() {
        try {
            Security.addProvider(new BouncyCastleProvider());
            // 1、创建密钥生成器
            KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM, "BC");
            keyGenerator.init(56);
            // 2、产生密钥
            SecretKey secretKey = keyGenerator.generateKey();
            // 3、获取密钥
            byte[] key = secretKey.getEncoded();
            return key;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 加密
    public static byte[] encrypt(byte[] data, byte[] key) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
            // 加工作模式和填充方式
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] rsData = cipher.doFinal(data);
            return rsData;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 解密
    public static byte[] decrypt(byte[] data, byte[] key) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
            // 加工作模式和填充方式
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] rsData = cipher.doFinal(data);
            return rsData;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        byte[] data = "32092210000000000000".getBytes(Charset.forName("UTF-8"));
        byte[] key = getKey();

        String hexKeyStr = Hex.toHexString(key);
        System.out.println("加密密钥:" + hexKeyStr + ",length=" + hexKeyStr.length());
        byte[] encryptData = encrypt(data, key);
        System.out.println("加密数据:" + Hex.toHexString(encryptData));
        byte[] decryptData = decrypt(encryptData, key);
        System.out.println("解密数据:" + new String(decryptData));
    }
}
